import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    Stock_BillListDto,
    GetStock_AuditInputDto,
    StockZT_ToolTransferServiceProxy,
    Stock_ToolTransferItemListDto,
    StockZT_AuditServiceProxy,
    ComboboxItemDto,
    SessionServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
// import { ExcelModalComponent } from '@app/shared/common/excel-modal/excel-modal.component';
import { CreateOrEditToolTransferModalComponent } from './create-or-edit-tool-transfer-modal.component';
import { UserDataPermissionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { finalize } from 'rxjs/operators';
import { CreateToolTransferOpinionModalComponent } from './create-or-edit-tool-transfer-opinion-modal.component';
@Component({
    templateUrl: './tool-transfer.component.html',
    animations: [appModuleAnimation()],
    selector: 'tooltransfer'
})
export class ToolTransferComponent extends AppComponentBase {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;
    @ViewChild('createOrEditToolTransferModal')
    createOrEditToolTransfersBillModal: CreateOrEditToolTransferModalComponent;
    @ViewChild('createToolTransferOpinionModalComponent')
    createToolTransferOpinionModalComponent: CreateToolTransferOpinionModalComponent;
    // @ViewChild('excelModal') excelModal: ExcelModalComponent;
    // filters
    deptFilter = '';
    searchOutDept = '';
    searchInDept = '';
    materialNameFilter = '';
    certificationNumFilter = '';
    reCheckFilter = '';
    supplierFilter = '';
    warehouseNameFilter = '';
    uploadUrl;

    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;

    detailPrimengTableHelper: PrimengTableHelper;
    primengTableHelper: PrimengTableHelper;
    selectedBill: Stock_BillListDto;
    selectedBillItem = new Stock_ToolTransferItemListDto();
    auditDto: GetStock_AuditInputDto;
    optionbillBase = [{ label: '全部', value: undefined }, { label: '当前用户', value: '当前用户' }];
    f_isCurrentUser; //是否当前用户-查询用
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已审核', value: '已审核' },
        { label: '已出库', value: '已出库' }
    ];
    f_billStatues; //单据状态-查询用
    selectedDepts: any;
    materialCodeFilter: any;
    billcode: any;
    billstatus: any;
    userDataPermissions;
    PlanNumber='';
    ContractNumber='';
    constructor(
        injector: Injector,
        private _billBaseService: StockZT_ToolTransferServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _auditService:StockZT_AuditServiceProxy,
        private _base_SessionServiceProxy: SessionServiceProxy
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
        this.primengTableHelper = new PrimengTableHelper();
    }
    ngOnInit(): void {
        this._userDataPermissionServiceProxy.getUserDataPermissions('Base_Bill').subscribe(result => {
            this.userDataPermissions = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });
             this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
                       let ssData = new ComboboxItemDto();
                          ssData.value = result.value;
                          ssData.isSelected = false;
                           ssData.displayText = result.label;
                           let ss: ComboboxItemDto[] = [ssData];
                            this.selectedDepts = ss;
                            this.getBills();
                        });

        });
    }
    import() {
        // this.excelModal.show('Contract', '合同', '', 0);
        //     this.uploadUrl =
        //     AppConsts.remoteServiceBaseUrl +
        //     '/File/ImportStockInfoFromExcel?type=' +
        //     '1' +
        //     '&year=' +
        //     '1' +
        //     '&month=' +
        //    '1' +
        //     '&taskNum=' +
        //     '1';
        //     this._httpClient
        //     .post<any>(this.uploadUrl,'').subscribe(response => {
        //         if (response.error != null) {
        //             this.message.error(this.l('导入失败,' + response.error.message));
        //         } else {
        //             if (response.result.fileName) {
        //                 this._fileDownloadService.downloadTempFile(response.result);
        //                 if (response.success) {
        //                     this.notify.success('部分导入成功');
        //                 }
        //             } else {
        //                 if (response.success) {
        //                     this.notify.success('导入成功');
        //                 }
        //             }
        //         }
        //     });
    }

    getBills(event?: LazyLoadEvent, resetpage?: boolean) {
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            if(resetpage == undefined) {
                this.paginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billBaseService
            .getToolTransferBaseListExtension(
                undefined,
                this.selectedDepts,
                this.materialCodeFilter,
                this.billcode,
                this.PlanNumber,
                this.ContractNumber,
                this.billstatus,
                '',
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_ToolTransferBaseList.totalCount;
                this.primengTableHelper.records = result.stock_ToolTransferBaseList.items;

                this.detailPrimengTableHelper.totalRecordsCount = 0;
                this.detailPrimengTableHelper.records = null;

                this.selectedBill = null;
                this.selectedBillItem = null;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
    //提交/审核
    submitBill() {
        if (this.selectedBill.f_BillStatus != '新建') {
            this.message.warn('已提交或已审核！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.totalRecordsCount <= 0) {
            this.message.warn('没有添加明细，不能提交');
            return;
        }
        this.auditDto = new GetStock_AuditInputDto();
        this.auditDto.id = this.selectedBill.id;
        this.message.confirm('确认提交？', isConfirmed => {
            if (isConfirmed) {
                this._billBaseService.submitToolTransferBillBase(this.selectedBill.id).subscribe(() => {
                    this._billBaseService
                        .submitToolAuditBill(this.auditDto)
                        .pipe(
                            finalize(() => {
                                this.primengTableHelper.hideLoadingIndicator();
                            })
                        )
                        .subscribe(() => {
                            this.notify.success(this.l('提交成功'));
                            this.getBills(undefined, true);
                            this.primengTableHelper.hideLoadingIndicator();
                        });
                });
            }
        });
    }
    //提交/审核
    auditBill() {
        if (this.selectedBill.f_BillStatus != '已提交') {
            this.message.warn('未提交或已审核完毕！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        this._auditService.isCurrentNodeUserByBillId(this.selectedBill.id).subscribe(result => {
            if(result){
                this.auditDto = new GetStock_AuditInputDto();
                this.auditDto.id = this.selectedBill.id;
                this.createToolTransferOpinionModalComponent.show(this.selectedBill, '0');
            }else{
                this.message.warn("您不是当前审核人");
            }
        });
    }
    //过账
    postBill() {
        if (this.selectedBill.f_BillStatus != '已审核') {
            this.message.warn('未审核完毕，不能过账');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        this.message.confirm('确认过账？', isConfirmed => {
            if (isConfirmed) {
                this._billBaseService.postToolTransferBillBase(this.selectedBill.id).subscribe(() => {
                    this.notify.success(this.l('过账成功'));
                    this.getBills(undefined, true);
                });
            }
        });
    }
    //退回
    sendBackBill() {
        if (this.selectedBill.f_BillStatus == '已审核') {
            this.message.warn('已审核，不能退回！');
            return;
        }
        if (this.selectedBill.f_Posted == '已过帐') {
            this.message.warn('已过账，不能退回！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        this.auditDto = new GetStock_AuditInputDto();
        this.auditDto.id = this.selectedBill.id;
        this.createToolTransferOpinionModalComponent.show(this.selectedBill, '1');
    }

    //编辑
    edit() {
        if (this.selectedBill.f_BillStatus != '新建') {
            this.message.warn('已提交不能编辑');
        } else {
            this.createOrEditToolTransfersBillModal.show(this.selectedBill.id);
        }
    }

    reloadData(event) {
        if (event == null || event == undefined) {
            this.getBills();
        } else {
            this.getBillItems();
        }
    }
    getBillItems(event?: LazyLoadEvent) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            this.detailPaginator.changePage(0);

            return;
        }
        this.detailPrimengTableHelper.showLoadingIndicator();

        this._billBaseService
            .getToolTransferItemListExtension(
                this.selectedBill.id,
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.stock_ToolTransferItemList.totalCount;
                this.detailPrimengTableHelper.records = result.stock_ToolTransferItemList.items;
                this.detailPrimengTableHelper.hideLoadingIndicator();

                this.selectedBillItem = null;
            });
    }

    deleteBill() {
        if (this.selectedBill.f_BillStatus != '新建') {
            this.message.warn('已提交或已审核，不能删除！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this._billBaseService.deleteToolTransferBase(this.selectedBill.id).subscribe(() => {
                    this.notify.success(this.l('SuccessfullyDeleted'));
                    this.getBills();
                });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this._billBaseService.deleteToolTransferItem(this.selectedBillItem.id).subscribe(() => {
                    this.notify.success(this.l('SuccessfullyDeleted'));
                    this.getBillItems();
                });
            }
        });
    }

    importEnd(event: boolean) {
        if (event) {
            this.getBills();
        } else {
            this.primengTableHelper.hideLoadingIndicator();
        }
    }
}
